import React from 'react';
import {
  TouchableOpacity,
  View,
  Text,
} from 'react-native';

import ToastUtils from '../common/ToastUtils';
import Config from '../config';
import SizeUtils from '../common/SizeUtils';
import Constants from '../common/Constants';
import TComponent from './TComponent';
import TImage from './TImage';
import DataManager from '../datas/DataManager';
import CommonShowImageFullScreenAction from '../actions/common/CommonShowImageFullScreenAction';

const IMAGE_SCALE = 0.3;
const IMAGE_MAX_SIZE = 800;//K
//上传单个图片控件
export default class TImageUpLoadOneComponent extends TComponent {
  constructor(props) {
    super(props);

    // this.props.containerStyle
    // this.props.imageStyle
    // this.props.viewStatusConstants [{viewStatus:101, source:require("******")}...]
    // this.props.disableViewStatus [101, 102...]
    // this.props.onUpdateCallback 更新信息回调
    // this.props.imageData

    this.state.isUploadingImage = false;

    //本地选择图片得到的数据
    this._imageResponse = null;
    //传进来的数值
    this._imageData = this.props.imageData === undefined ? null : this.props.imageData;
    //是否在选择图片
    this._isSelectedingImage = false;
    //控件
    this._imagePicker = require('react-native-image-picker');
    this._updateDataCallback = this.props.onUpdateData;
    this.state.updateDataMark = 0;

    console.log("new TImageUpLoadOneComponent", this._imageData);
  }

  // shouldComponentUpdate(nextProps, nextState) {
  //   if(this._imageData && nextProps.imageData && this._imageData.data === nextProps.imageData.data) {
  //     return false;
  //   }
  //   return true;
  // }

  componentWillUpdate(nextProps, nextState) {
    // console.log("update TImageUpLoadOneComponent", this._imageData, nextProps.imageData);
    //更新imageUrl
    if(this.props.imageData != nextProps.imageData) {
      this._imageData = nextProps.imageData === undefined ? null : nextProps.imageData;
    }
  }

  reset() {
    this._imageData = null;
  }

  render() {
    if(this.props.visible === false) {
      return (<View></View>);
    }
    return(
      <View style={[{backgroundColor:"#66666633"}, this.props.style]}>
        <TouchableOpacity style={{width:this._getContainerStyle().width,
              height:this._getContainerStyle().height,}}
            onPress={() => this._onPressImage()}>
          <TImage source={this._getImageSource()} resizeMode={"contain"}
            style={{width:this._getImageStyle().width, height:this._getImageStyle().height}} />
          {this._renderCloseButton()}
        </TouchableOpacity>
        {this._renderLoadingView()}
      </View>
     )
  }

  _renderLoadingView() {
    if(this.state.isUploadingImage === false) {
      return;
    }
    return (
      <View style={{position:"absolute", width:this.props.style.width,
            height:this.props.style.height, backgroundColor:"#00000066",
            flexDirection:"row", justifyContent:"center", alignItems:"center"}}>
          <Text style={{flex:1, textAlign:"center"}} >
            上传中...
          </Text>
      </View>
    )
  }

  doUpload(callback) {
    console.log("开始上传单个图片 doUpload", this._imageData);
    if(this._imageData.type === "local") {
      var key = Constants.RANDOM_UPLOAD_NAME(25) + this._imageData.response.fileName;
      this.state.isUploadingImage = true;
      DataManager.modelDic[Constants.MODULE_TYPE.ALI_OSS].uploadFile(key, this._imageData.response.uri, function(pre, res){
        this.state.isUploadingImage = false;
        console.log("单个图片上传完成 ", this._imageData);
        if(pre === undefined || pre == null) {
          callback(false)
        }
        else {
          let url = Config.aliUrl + pre + key;
          callback(true, url);
        }
      },this);
    }
    else {
      callback(true, null);
    }
  }


  _renderCloseButton() {
    if(this._imageData === null) {
      return;
    }
    return (
      <TouchableOpacity style={{position:"absolute", top:SizeUtils.translateDesignHeightToCode(10),
          right:SizeUtils.translateDesignWidthToCode(10)}} onPress={this._dealRemoveImage.bind(this)}>
        <TImage source={require("../../resource/images/common/closed2.png")} style={{width:28, height:28}}/>
      </TouchableOpacity>
    )
  }

  _getImageStyle() {
    return this.props.imageStyle === undefined ? {width:100, height:100} : this.props.imageStyle;
  }

  _getContainerStyle() {
    return this.props.containerStyle === undefined ? {width:SizeUtils.translateDesignWidthToCode(this._getImageStyle().width),
        height:SizeUtils.translateDesignWidthToCode(this._getImageStyle().height),
      } : this.props.containerStyle;
  }

  _getImageSource() {
    if(this._imageData != null && this._imageData.response != null && this._imageData.response != undefined) {
      return {uri:this._imageData.response.uri};
    }
    else if(this.props.viewStatusConstants){
      for (var i = 0; i < this.props.viewStatusConstants.length; i++) {
        if(this.state.viewStatus === this.props.viewStatusConstants[i].viewStatus
            && this.props.viewStatusConstants[i].source != undefined) {
          return this.props.viewStatusConstants[i].source;
        }
      }
    }
    else if(this._imageData != null && this._imageData.data){
      return {uri:this._imageData.data};
    }
    else {
      return require("../../resource/images/common/plus.png");
    }
  }

  _onPressImage() {
    if(this._imageData != null) {
      new CommonShowImageFullScreenAction().call(this, {source:this._imageData.data,
        operateTypes:[{name:"delete", value:"删除"}], callback:(operateType) => this._imageFullScreenCallback(operateType)})
    }
    // else if (this._imageResponse != null) {
    //   new CommonShowImageFullScreenAction().call(this, {source:'data:image/png;base64,' + this._imageResponse.data, width:333, height:333,
    //     operateTypes:[{name:"delete", value:"删除"}], callback:(operateType) => this._imageFullScreenCallback(operateType)})
    // }
    else {
      this._selectImage();
    }
  }

  _imageFullScreenCallback(operateType) {
    if(operateType.name == "delete") {
      this._dealRemoveImage()
    }
  }

  _dealRemoveImage() {
    this._imageResponse = null;
    this._imageData = null;
    this._updateMark();
  }

  _selectImage(){
    if(this._isSelectedingImage){
      return;
    }
    var options = {
      title:'请选择',
      cancelButtonTitle:'取消',
      takePhotoButtonTitle:'拍照',
      chooseFromLibraryButtonTitle:'选择相册',
      quality:IMAGE_SCALE,
      storageOptions: {
        skipBackup: true,
        path: 'images'
      }
    };
    this._isSelectedingImage = true;
    this._imagePicker.showImagePicker(options, (response)=> {
      this._isSelectedingImage = false;
      if (response.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
        try {
          ToastUtils.show("获取图片失败" + response.error + "!");
        } catch (e) {
          ToastUtils.show("获取图片失败!");
        }
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {
        console.log("获取成功");
        console.log(response);
        if(response.fileSize < IMAGE_MAX_SIZE * 1024) {
          ToastUtils.show("获取图片成功!");
          this._imageResponse = response;
          this._imageData = {type:"local", data:'data:image/png;base64,' + this._imageResponse.data, response:this._imageResponse};
          this._updateMark();
        }
        else {
          ToastUtils.show("图片大小不能大于" + Math.floor(IMAGE_MAX_SIZE / IMAGE_SCALE) + "k");
        }
      }
    });
  }

  _updateMark() {
    this.props.onUpdateCallback && this.props.onUpdateCallback(this.props.imageData, this._imageData);
    this._imageData = null;
    this._imageResponse = null;
    this.setState({
      updateDataMark: this.state.updateDataMark + 1,
    })
  }
}
